<template>
  <el-dialog v-model="visible" :title="title">
    <el-form ref="formRef" :rules="rules" :model="form" label-width="11em">
      <el-form-item label="所属应用" prop="app">
        <el-select-v2
          v-model="form.app"
          placeholder="选择所属应用"
          :options="thirdAppStore.list"
          :props="{ value: 'id', label: 'name' }"
        />
      </el-form-item>
      <el-form-item label="API Key" prop="key">
        <el-input v-model="form.key" placeholder="输入API Key" />
      </el-form-item>
      <el-form-item label="是否启用" prop="is_active">
        <el-switch v-model="form.is_active" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="apiKeyStore.loading.submit" @click="handleSubmit">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { useApiKeyStore } from "@/store/modules/system/api-key";
import { useThirdAppStoreHook } from "@/store/modules/system/third-app";
import type { FormInstance, FormRules } from "element-plus";
import { cloneDeep } from "lodash-es";
import { ApiKeyForm } from "@/api/system/api-key";

export type FormType = "add" | "edit";

const props = defineProps({
  modelValue: Boolean,
  type: {
    type: String as () => "add" | "edit",
    default: "add",
  },
  form: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(["update:modelValue", "confirm"]);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const defaultForm: ApiKeyForm = {
  app: "",
  is_active: true,
  key: "",
};

const form = reactive<ApiKeyForm>(cloneDeep(defaultForm));

const title = computed(() => (props.type === "add" ? "添加API Key" : "编辑API Key"));

const apiKeyStore = useApiKeyStore();
const thirdAppStore = useThirdAppStoreHook();

const formRef = ref<FormInstance>();
const rules = ref<FormRules>({
  app: [{ required: true, message: "请选择所属应用", trigger: "change" }],
  key: [{ required: true, message: "请输入API Key", trigger: "change" }],
});

watch(visible, async (val) => {
  if (val) {
    await thirdAppStore.fetchList({ page: 1, size: 99999 });
    if (props.type == "edit") {
      Object.assign(form, props.form);
    }
  } else {
    formRef.value?.resetFields();
    Object.assign(form, cloneDeep(defaultForm));
  }
});

async function handleSubmit() {
  try {
    await formRef.value?.validate();
    if (props.type === "add") {
      await apiKeyStore.fetchAdd(form);
    } else {
      await apiKeyStore.fetchUpdate(props.form);
    }
    emit("confirm");
    visible.value = false;
  } catch (e) {
    console.error(e);
  }
}
</script>
